<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div{
            position: absolute;
            left: 0;
            top: 50px;
            width: 100px;
            height: 100px;
            background-color: #ff6700;

        }
    </style>
</head>
<body>
    <button class="btn500">移动500距离</button>
    <button class="btn800">移动800距离</button>
    <div></div>
    <script>
        function animate(obj, target, callback) {
            //先清除之前的定时器，防止多次点击开启多个定时器
            clearInterval(obj.timer);
            obj.timer = setInterval(function() {
                //定义步长器，必须写在定时器中 (目标值 - obj.offsetLeft) / 10
                var step = (target - obj.offsetLeft) / 10;
                step = step > 0 ? Math.ceil(step) : Math.floor(step);
                if(obj.offsetLeft == target) {
                    clearInterval(obj.timer);
                    //定时器结束后如果有回调函数，则开始调用
                    if(callback) {
                        callback();
                    }
                }
                obj.style.left = obj.offsetLeft + step + 'px';
            },15)
        }
        var btn500 = document.querySelector('.btn500');
        var btn800 = document.querySelector('.btn800');
        var div = document.querySelector('div');
        btn500.addEventListener('click', function() {
            animate(div, 500, function() {
                //回调函数
                div.style.backgroundColor = '#ff6700';
            });
        });
        btn800.addEventListener('click', function() {
            animate(div, 800, function() {
                //回调函数
                div.style.backgroundColor = 'skyblue';
            });
        })
    </script>
</body>
</html>